package com.example.simple;

import java.util.HashMap;
import java.util.Map;

/**
 * 简单的IoC容器实现
 * 演示控制反转的概念
 */
public class SimpleIoCContainer {
    
    private static final Map<String, Object> beans = new HashMap<>();
    private static final Map<String, Class<?>> beanDefinitions = new HashMap<>();
    
    /**
     * 注册Bean定义
     */
    public static void registerBean(String name, Class<?> clazz) {
        beanDefinitions.put(name, clazz);
    }
    
    /**
     * 获取Bean实例
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        // 检查是否已经创建过实例
        if (beans.containsKey(name)) {
            return (T) beans.get(name);
        }
        
        // 获取Bean定义
        Class<?> clazz = beanDefinitions.get(name);
        if (clazz == null) {
            throw new RuntimeException("Bean '" + name + "' not found");
        }
        
        try {
            // 创建实例
            Object instance = clazz.getDeclaredConstructor().newInstance();
            beans.put(name, instance);
            return (T) instance;
        } catch (Exception e) {
            throw new RuntimeException("Failed to create bean '" + name + "'", e);
        }
    }
    
    /**
     * 获取Bean实例（通过类型）
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> clazz) {
        for (Map.Entry<String, Class<?>> entry : beanDefinitions.entrySet()) {
            if (clazz.isAssignableFrom(entry.getValue())) {
                return (T) getBean(entry.getKey());
            }
        }
        throw new RuntimeException("Bean of type '" + clazz.getName() + "' not found");
    }
    
    /**
     * 清空容器
     */
    public static void clear() {
        beans.clear();
        beanDefinitions.clear();
    }
}
